package com.jiantong.news.impl.service;

import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.jiantong.news.impl.dao.NewsDao;
import com.jiantong.news.model.News;
import com.jiantong.news.service.NewsReadService;
import io.terminus.boot.rpc.common.annotation.RpcProvider;
import io.terminus.common.model.PageInfo;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**首页\新闻
 * Created by mz03 on 2017/3/15.
 * zyp
 */
@Slf4j
@Service
@RpcProvider
public class NewsReadServiceImpl implements NewsReadService{

    private final NewsDao newsDao;

    @Autowired
    public NewsReadServiceImpl(NewsDao newsDao) {
        this.newsDao = newsDao;
    }

    /**
     * id 查找
     * @param id
     * @return News
     * Response<News> finById(Long id);
     */
    @Override
    public Response<News> finById(Long id) {
        try{
            News news = newsDao.findById(id);
            if(news == null){
                //判断根据id查出来的结果,判断其如果是空值 抛异常信息
                log.error("news (id={}) is not found", id);
                return Response.fail("news.not.found");
            }
            return Response.ok(news);
        } catch (Exception e) {
            log.error("failed to find news(id={}),cause:{}",id, Throwables.getStackTraceAsString(e));
            return Response.fail("news.find.fail");
        }

    }

    /**
     * type 查找
     * @param type
     * @return List<News>
     */
    @Override
    public Response<List<News>> finByType(Integer type) {
        try {
            return Response.ok(newsDao.findByType(type));
        }catch (Exception e){
            log.error("find by news type:{} fail,cause:{}",Throwables.getStackTraceAsString(e));
            return Response.fail("find.news.fail");
        }
    }

    /**
     *
     * @param pageNo 页码
     * @param pageSize 条数
     * @param type 类型
     * @return
     */
    @Override
    public Response<Paging<News>> pagingNews(Integer pageNo, Integer pageSize, Integer type) {
        try{
            PageInfo pageInfo = new PageInfo(pageNo,pageSize);
            Map<String, Object> criteria = Maps.newHashMap();
            if(type != null){
                criteria.put("type",type);
                //在这里加入状态判断是否可以传入?
                criteria.put("status",1);
            }
            return Response.ok(newsDao.paging(pageInfo.getOffset(),pageInfo.getLimit(),criteria));
        }catch (Exception e){
            log.error("failed to find News(type={}), cause:{}", type, Throwables.getStackTraceAsString(e));
            return Response.fail("News.find.fail");
        }
    }

}
